package com.cff.netty.anno.self;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.cff.anno.AutoDi;
import com.cff.proxy.HandlerProxy;
import com.cff.service.HandlerService;
import com.cff.service.HelloWorldService;

public class NettyServerAnnoSelfHandler extends SimpleChannelInboundHandler<String>{
	private Map<String, Object> exportServiceMap;
	
	@AutoDi
	HandlerService handlerService;
	
	@Autowired
	HelloWorldService helloWorldService;
	
	public NettyServerAnnoSelfHandler(Map<String, Object> exportServiceMap) throws IllegalArgumentException, IllegalAccessException {
		this.exportServiceMap = exportServiceMap;
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field f : fields) {
			Annotation[] annos = f.getAnnotationsByType(AutoDi.class);
			Annotation[] annos2 = f.getAnnotationsByType(Autowired.class);
			if((annos != null && annos.length >0)|| (annos2 !=null && annos2.length >0)){
				f.setAccessible(true);
				f.set(this, exportServiceMap.get(f.getName()));
				f.setAccessible(false);
			}
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {		
//		System.out.println(((HandlerServiceImp) exportServiceMap.get("helloWorldService")).test());
//		// 返回客户端消息 - 我已经接收到了你的消息
//		ctx.writeAndFlush("Received your message !\n");
		System.out.println(Thread.currentThread().getName()+"----位置6");
		handlerService.handle(msg);
		ctx.writeAndFlush("Received your message !\n");
		helloWorldService.handle();
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + " channelRegistered " );
		super.channelRegistered(ctx);
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + " channelUnregistered " );
		super.channelUnregistered(ctx);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + " channelActive " );
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + " channelInactive " );
		super.channelInactive(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + " exceptionCaught :" + cause.getMessage() );
		super.exceptionCaught(ctx, cause);
	}

}
